<?php
class ControllerSalePartialpayment extends Controller
{
    public function index()
    {
        if(!isset($this->request->get['order_id']) || !$id=$this->request->get['order_id']) return false;

        $this->template='sale/partial_payment.tpl';

        $this->load->language('sale/order');
        $orderModel=$this->model->load('orderModel');
        //$orderProdModel=$this->model->load('orderProductModel');
        $orderProdPartialModel=$this->model->load('orderProductPartialModel');
        $this->model->load('customerModel')->getDebt(1);

        $this->data['partial_payment']=$this->language->get('partial_payment');
        $this->data['column_product']=$this->language->get('column_product');
        $this->data['column_model']=$this->language->get('column_model');
        $this->data['column_quantity']=$this->language->get('column_quantity');
        $this->data['column_price']=$this->language->get('column_price');
        $this->data['column_total']=$this->language->get('column_total');
        $this->data['column_payment']=$this->language->get('column_payment');
        $this->data['column_status']=$this->language->get('column_status');
        $this->data['column_paid']=$this->language->get('column_paid');
        $this->data['column_remaining_pay']=$this->language->get('column_remaining_pay');
        $this->data['error_quantity']=$this->language->get('error_quantity');
        $this->data['error_money']=$this->language->get('error_money');

        if(!$order=$orderModel->findByPk($id))  return false;
        if(!$products=$orderProdPartialModel->findAllByAttributes(array('order_id'=>$id))) return false;

        $this->load->model('setting/extension');
        $extensions=$this->model_setting_extension->getInstalled('payment');
        $payments=array();
        foreach($extensions as $ext){
            if(file_exists(DIR_APPLICATION.'controller/payment/'.$ext.'.php')){
                $this->load->language('payment/'.$ext);
                $payments[$ext]=$this->language->get('heading_title');
            }
        }

        $this->data['products']=$products;
        foreach($products as $num=>$prod){
            $this->data['products'][$num]['total']=$prod['price']*$prod['quantity'];
            $this->data['products'][$num]['productPayment']=$payments[$prod['payment_code']];
            $this->data['products'][$num]['payment']=$payments;
            $this->data['products'][$num]['partial_id']=$prod['order_product_partial_id'];
            $this->data['products'][$num]['productStatus']=$prod['status'];
            $this->data['products'][$num]['status']=array(
                $this->language->get('no_paid'),
                $this->language->get('paid'),
            );
        }

        $this->data['status']=$orderModel->getStatus($id);

        $this->response->setOutput($this->render());
    }

    public function add_to_partial()
    {
        $this->template='sale/add_to_partial_payment.tpl';
        $this->load->language('sale/order');
        $prodModel=$this->model->load('orderProductModel');
        $orderModel=$this->model->load('orderModel');

        $orderId=$this->request->get['order_id'];
        $productId=$this->request->get['product_id'];
        $quantity=$this->request->get['quantity'];

        $this->data['orderId']=$orderId;
        $this->data['productId']=$productId;
        $this->data['quantity']=$quantity;
        $this->data['error_warning']='';
        $this->data['success']='';

        $this->data['partial_payment']=$this->language->get('partial_payment');
        $this->data['column_product']=$this->language->get('column_product');
        $this->data['column_model']=$this->language->get('column_model');
        $this->data['column_quantity']=$this->language->get('column_quantity');
        $this->data['column_price']=$this->language->get('column_price');
        $this->data['column_total']=$this->language->get('column_total');
        $this->data['column_payment']=$this->language->get('column_payment');
        $this->data['select_payment']=$this->language->get('select_payment');
        $this->data['action']=$this->url->link('sale/partial_payment/add_to_partial','token='.$this->request->get['token']);
        $this->data['confirm']=$this->language->get('button_save');
        $this->data['column_status']=$this->language->get('column_status');
        $this->data['column_paid']=$this->language->get('column_paid');

        $order=$orderModel->findByPk($orderId);
        $this->data['prodPayment']=$order['payment_code'];

        $this->load->model('setting/extension');
        $extensions=$this->model_setting_extension->getInstalled('payment');

        $this->data['payments']=array();
        foreach($extensions as $ext){
            if(file_exists(DIR_APPLICATION.'controller/payment/'.$ext.'.php')){
                $this->load->language('payment/'.$ext);
                $this->data['payments'][$ext]=$this->language->get('heading_title');
            }
        }

        $this->data['product']=$prodModel->findByPk($productId);
        $this->data['productStatus']=0;
        $this->data['product']['money']=0;
        $this->data['product']['status']=array(
            $this->language->get('no_paid'),
            $this->language->get('paid'),
        );

        $this->children=array(
            'common/header',
            'common/footer',
        );

        $this->response->setOutput($this->render());
    }

    public function add_to_partial_ajax()
    {
        $json=array(
            'error'=>'',
            'success'=>'',
            'result'=>0,
        );

        if(isset($this->request->get['payment'])){

            try{
                $orderId=$this->request->get['order_id'];
                $productId=$this->request->get['product_id'];
                $quantity=$this->request->get['quantity'];

                $this->load->language('sale/order');
                $orderProduct=$this->model->load('orderProductModel')->findByPk($productId);
                $total=$orderProduct['price']*$quantity;

                $result=false;

                $status=$this->request->get['status'];
                $money=$this->request->get['money'];

                if($status){
                    $money=$total;
                    $moneyLeft=0;
                }else{
                    $moneyLeft=$total-$money;
                }

                if((int)$quantity>=0){
                    if((int)$moneyLeft>=0){

                        $attributes=array(
                            'order_id'=>$orderId,
                            'product_id'=>$productId,
                            'status_id'=>2,
                            'payment_code'=>$this->request->get['payment'],
                            'quantity'=>$quantity,
                            'name'=>$orderProduct['name'],
                            'model'=>$orderProduct['model'],
                            'price'=>$orderProduct['price'],
                            'status'=>$status,
                            'product_real_id'=>$orderProduct['product_id'],
                            'money'=>$money,
                            'money_left'=>$moneyLeft,
                        );

                        if($result=$this->model->load('orderProductPartialModel')->save($attributes)){
                            $orderModel=$this->model->load('orderModel');
                            $orderPartial=$orderModel->findModelAttributesByPk($orderId,array('partial_paid'));
                            if($orderPartial && is_array($orderPartial)){
                                $orderPartial=$orderPartial['partial_paid'];
                            }else
                                $orderPartial=0;

                            $result=$orderModel->update($orderId,array('partial_paid'=>$money+$orderPartial));
                        }
                    }else{
                        $json['error']=$this->language->get('error_money_left');
                    }

                    if($result){
                        $this->session->data['success']=$json['success']=$this->language->get('text_success');
                        $json['result']=1;
                    }else{
                        if(!$json['error']) $json['error']=$this->language->get('error_db');
                    }
                }else{
                    $json['error']=$this->language->get('error_quantity');
                }
            }catch(Exception $e){
                $json['error']=$e;
            }
        }

        $this->response->setOutput(json_encode($json));
    }

    public function delete_from_partial()
    {
        $json=array(
            'error'=>'',
            'success'=>'',
            'result'=>array(),
        );


        if(isset($this->request->get['partial_id'])){
            $orderId=isset($this->request->get['order_id']) ? $this->request->get['order_id'] : 0;

            $this->load->language('sale/order');
            $partialModel=$this->model->load('orderProductPartialModel');

            $partialId=$this->request->get['partial_id'];
            if($money=$partialModel->findModelAttributesByPk($partialId,array('money'))){
                if(is_array($money)) $money=$money['money'];
            }else
                $money=0;


            if($partialModel->delete($partialId)){
                $json['result']['partialId']=$partialId;
                $orderModel=$this->model->load('orderModel');
                $orderPartial=$orderModel->findModelAttributesByPk($orderId,array('partial_paid'));

                if($orderPartial && is_array($orderPartial) && $orderId && $money){
                    if($orderPartial=$orderPartial['partial_paid']) $orderModel->update($orderId,array('partial_paid'=>$orderPartial-$money));
                }
            }else
                $json['error']=$this->language->get('error_db');
        }

        $this->response->setOutput(json_encode($json));
    }

    public function partial_order()
    {
        $this->template='sale/order_partial.tpl';
        $this->load->language('sale/order');
        $id=$this->request->get['order_id'];

        $this->data['error_warning']='';
        $this->data['success']='';
        if(isset($this->session->data['error_warning'])){
            $this->data['error_warning']=$this->session->data['error_warning'];
            unset($this->session->data['error_warning']);
        }
        if(isset($this->session->data['success'])){
            $this->data['success']=$this->session->data['success'];
            unset($this->session->data['success']);
        }

        $model=$this->model->load('orderModel');
        $attributes=array(
            'order_id',
            'total',
            'partial_paid',
            'date_modified',
        );

        $this->data['action']=$this->url->link('sale/partial_payment/partial_order_ajax', 'token='.$this->session->data['token'].'&order_id='.$id);
        $this->data['order']=$model->findModelAttributesByPk($id,$attributes);
        $this->data['partial_payment']=$this->language->get('partial_payment');
        $this->data['column_total']=$this->language->get('column_total');
        $this->data['confirm']=$this->language->get('button_save');

        $this->children=array(
            'common/header',
            'common/footer',
        );

        $this->response->setOutput($this->render());
    }

    public function partial_order_ajax()
    {
        $json=array(
            'error'=>'',
            'success'=>'',
            'result'=>0,
        );

        if(isset($this->request->get['order_partial'])){
            $this->load->language('sale/order');
            $model=$this->model->load('orderModel');

            foreach($this->request->get['order_partial'] as $id=>$paid){
                if($paid!==null && $paid!==false){
                    $oldOrder=$model->findModelAttributesByPk($id,array('total'));

                    if($oldOrder['total']!=$paid && $oldOrder['total']>$paid){
                        if($model->update($id,array('partial_paid'=>$paid))){
                            $this->session->data['success']=$json['success']=$this->language->get('text_success');
                            $json['result']=1;
                        }
                    }else{
                        $json['error']=$this->language->get('partial_error');
                    }
                }
            }
        }

        $this->response->setOutput(json_encode($json));
    }
}